//
//  XGChatMessageViewController.m
//  HuanXin
//
//  Created by monkey on 2019/11/22.
//  Copyright © 2019 itcast. All rights reserved.
//

#import <Masonry/Masonry.h>
#import <Hyphenate/Hyphenate.h>
#import <SVProgressHUD/SVProgressHUD.h>

#import "XGChatMessageViewController.h"

#import "XGUserModel.h"

#import "XGChatMenuView.h"

@interface XGChatMessageViewController () <UITableViewDelegate,XGChatMenuViewDelegate>
{
    XGUserModel *_userModel;
    EMConversation *_conversation;
}

/// 信息列表
@property (nonatomic,strong) UITableView *messageTableView;
/// 工具栏
@property (nonatomic,strong) XGChatMenuView *menuView;

@end

@implementation XGChatMessageViewController

#pragma mark - 构造方法

- (instancetype)initWithUserModel:(XGUserModel *)userModel
{
    if (self = [super init]) {
        _userModel = userModel;
        _conversation = [[EMClient sharedClient].chatManager getConversation:userModel.userName type:EMConversationTypeChat createIfNotExist:YES];
    }
    
    return self;
}

#pragma mark - 控制器生命周期方法

- (void)loadView
{
    [super loadView];
    
    [self setUpUI];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrameNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];
    self.navigationItem.title = _userModel.userName;
    
    [_conversation loadMessagesStartFromId:nil count:10 searchDirection:EMMessageSearchDirectionUp completion:^(NSArray *aMessages, EMError *aError) {
        for (EMMessage *message in aMessages) {
            EMTextMessageBody *body = (EMTextMessageBody *)message.body;
            DEBUG_Log(@"%@",body.text);
        }
    }];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 事件监听

- (void)keyboardWillChangeFrameNotification:(NSNotification *)notification
{
    CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGFloat endY = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
    CGFloat offset = endY - [XGCommon shared].screenHeight;
    offset += offset == 0 ? -[XGCommon shared].bottomMargin : 0;
    [_menuView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(offset);
    }];
    
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
}

#pragma mark - UITableViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [_menuView endEditing:YES];
}

#pragma mark - XGChatMenuViewDelegate

- (void)chatMenuView:(XGChatMenuView *)chatMenuView sendMessage:(NSString *)message
{
    [_menuView endEditing:YES];
    
    // 生成Message
    EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:message];
    NSString *from = [[EMClient sharedClient] currentUsername];
    EMMessage *sendMessage = [[EMMessage alloc] initWithConversationID:_conversation.conversationId from:from to:_userModel.userName body:body ext:nil];
    // 设置为单聊消息
    sendMessage.chatType = EMChatTypeChat;
    [[EMClient sharedClient].chatManager sendMessage:sendMessage progress:nil completion:^(EMMessage *message, EMError *error) {
        if (error) {
            [SVProgressHUD showErrorWithStatus:@"发送消息失败!"];
            return;
        }
    }];
}

#pragma mark - 其他方法

- (void)setUpUI
{
    self.view.backgroundColor = [UIColor whiteColor];

    [self.view addSubview:self.messageTableView];
    [self.view addSubview:self.menuView];
    CGFloat bottomMargin = [XGCommon shared].bottomMargin;
    [_menuView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-bottomMargin);
    }];
    
    [_messageTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(_menuView.mas_top);
    }];
}

#pragma mark - 懒加载

- (UITableView *)messageTableView
{
    if (!_messageTableView) {
        _messageTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _messageTableView.delegate = self;
        _messageTableView.tableFooterView = [[UIView alloc] init];
    }
    
    return _messageTableView;
}

- (XGChatMenuView *)menuView
{
    if (!_menuView) {
        _menuView = [[XGChatMenuView alloc] init];
        _menuView.backgroundColor = [UIColor whiteColor];
        _menuView.delegate = self;
    }
    
    return _menuView;
}
@end
